# -*- coding: utf-8 -*-
# @Time    : 2020/8/6 16:21
# @Author  : wangYong
# @Email   : wangyong@xkw.cn
# @File    : ip_requests.py
# @ProjectName: python_project
import time

import requests
import re
import json
import random


from isChina import is_china


def request_ip(IP):
    url = 'https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?query={}&co=&resource_id=6006&t=1596701919290&ie=utf8&oe=gbk&cb=op_aladdin_callback&format=json&tn=baidu&cb=jQuery1102024526543245333277_1596701803731&_=1596701803746'.format(IP)

    headers = {
        'User-Agent': 'Mozilla/5.0',
        'Sec-Fetch-Site': 'same-site',
        'Sec-Fetch-Mode': 'no-cors',
        'Sec-Fetch-Dest':'script',
        'Referer':'https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&rsv_idx=1&tn=baidu&wd={}&fenlei=256&rsv_pq=b7b4eb4800037123&rsv_t=2578gnyDaVQlV9godJ%2Bek4Ek%2F5e5PnmGEfi9%2F7uYyGD1nkoA3RGzn7WAWGY&rqlang=cn&rsv_enter=1&rsv_dl=tb&rsv_sug3=18&rsv_sug1=11&rsv_sug7=100&rsv_sug2=0&rsv_btype=i&inputT=4894&rsv_sug4=23261'.format(IP),
        'Host':'sp0.baidu.com'
    }
    res = requests.get(url=url,headers=headers)

    ret = re.findall('\((.*?)\)',res.text)
    try:
        if len(ret) != 0:
            dic = json.loads(ret[0])
            return dic['data'][0]['location']
    except Exception as e:
        print(e)


def remove_list_empty(lic):
    return [li for li in lic if li !='']


def read_ip():
    fd = open('output_ip513_20000.txt','a',encoding='utf-8')
    with open('20000.txt',mode='r',encoding='utf8') as fp:
        for f in fp:
            lists = remove_list_empty(f.strip().split(' '))
            try:
                if len(lists) != 0 :
                    time.sleep(random.choice([0.1,0.05,0.02,0.01]))
                    addr = request_ip(lists[0])

                    fd.write("IP:"+lists[0]+'   攻击次数：'+lists[1]+'   攻击来源目的地：'+addr+'\n')
                    fd.flush()
                    # print("IP:"+lists[0]+'   攻击次数：'+lists[1]+'   攻击来源目的地：'+addr)
            except Exception as e:
                print(e)
            finally:
                print(lists)
    return '执行完成'


def ip_sorted():
    sort_ip = []
    fd = open('output_ip_sort_514.txt', 'a', encoding='utf-8')
    with open('514.txt','r',encoding='utf-8') as fp:
        for f in fp:
            lists = remove_list_empty(f.strip().split(' '))
            if is_china(lists[2][0:2]):
                if len(lists) == 3:
                    sort_ip.append((lists[0],lists[1],lists[2]))
                else:
                    sort_ip.append((lists[0], lists[1], lists[2]+lists[3]))

    sort_ip = sorted(sort_ip,key=lambda sor: int(sor[1]),reverse=True)
    for li in sort_ip:
        fd.write("IP:" + li[0] + '   攻击次数：' + li[1] + '   攻击来源目的地：' + li[2] + '\n')

    fd.close()


read_ip()
